﻿using Fluent.Logging;
using OpenQA.Selenium;
using OpenQA.Selenium.Support.UI;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Fluent.Light
{
    public static class WebDriverExtension
    {
        public static class HtmlAttributes
        {
            public const string ID = "id";
            public const string NAME = "name";
            public const string CLASS = "class";
            public const string VALUE = "value";
            public const string OUTHTML = "outHTML";
            public const string INNERHTML = "innerHTML";
            public const string WIDTH = "width";
            public const string HEIGHT = "height";
            public const string HREF = "href";
            public const string SRC = "src";
        }

        public static TResult Wait<TResult>(this IWebDriver webdriver, Func<IWebDriver, TResult> condition,
            double timeOut = default(double),
            double sleepInterval = default(double),
            string errorMessage = "")
        {
            TResult result = default(TResult);
            WebDriverWait waitAPI;

            if (sleepInterval != default(double))
            {
                waitAPI = new WebDriverWait(new SystemClock(),
                    webdriver,
                    timeOut == default(double) ? TimeSpan.FromMilliseconds(120000) : TimeSpan.FromMilliseconds(timeOut),
                    TimeSpan.FromMilliseconds(sleepInterval));
            }
            else
            {
                waitAPI = new WebDriverWait(webdriver,
                     timeOut == default(double) ? TimeSpan.FromMilliseconds(120000) : TimeSpan.FromMilliseconds(timeOut));
            }

            try
            {
                result = waitAPI.Until<TResult>(condition);
            }
            catch (WebDriverTimeoutException timeoutEx)
            {
                Log.Information(timeoutEx.Message);
            }
            catch (WebDriverException webDriverEx)
            {
                Log.Information(webDriverEx.Message);
            }
            catch (Exception ex)
            {
                if (!string.IsNullOrWhiteSpace(errorMessage))
                {
                    throw new Exception(errorMessage, ex);
                }
            }

            return result;
        }

        public static string Value(this IWebElement _element)
        {
            return _element.GetAttribute(HtmlAttributes.VALUE);
        }

        public static void SetText(this IWebElement _element, string text)
        {
            Log.Information("Set text: {0}", text);

            _element.Clear();
            _element.SendKeys(text);

            Log.Information("Then get the current value is: {0}", _element.Value());
        }
    }
}
